package com.lyb.app;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.lyb.BuildConfig;
import com.lyb.R;
import com.lyb.config.ConfigUtil;
import com.lyb.config.Constant;
import com.lyb.config.KeyConfig;
import com.lyb.events.BaseEvent;
import com.lyb.events.EventController;
import com.lyb.ui.login.activity.LoginActivity;
import com.lyb.ui.login.activity.RegisterPhoneActivity;
import com.lyb.ui.main.MainActivity;
import com.lyb.util.LogUtils;
import com.lyb.util.SpUtil;
import com.lyb.util.StringUtil;
import com.lyb.util.TestDeviceUtil;
import com.lyb.util.ToastUtil;
import com.lyb.util.ViewUtil;
import com.meituan.android.walle.WalleChannelReader;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import cn.jpush.android.api.JPushInterface;


public class App extends Application {

    public static App mApp;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        //突破Dex文件方法数不能超过最大值65536的上限
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mApp = this;
        //log初始化,根据configUtil的isDebug参数控制是否显示log
        LogUtils.logInit(getConfig().isDebug());
        //toast初始化
        ToastUtil.register(getContext());
        //注册eventbus
        EventBus.getDefault().register(this);
        //友盟相关功能初始化(统计与分享)
        initUM();
        initLoadingView(getContext());
        //极光推送
        initJPush();
    }

    private void initJPush() {
        JPushInterface.setDebugMode(getConfig().isDebug());    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);            // 初始化 JPush
    }


    public void initUM() {
        /*获取market*/
        String channel = WalleChannelReader.getChannel(getContext());
        if (TextUtils.isEmpty(channel)) {
            channel = getConfig().getChannelName();
        }
        LogUtils.loge("当前渠道:" + channel);
        /*注册UMENG*/
        MobclickAgent.startWithConfigure(new MobclickAgent.UMAnalyticsConfig(getContext(), KeyConfig.getUmengKey(), channel));
        getConfig().setChannelName(channel);

        //关闭默认统计
        MobclickAgent.openActivityDurationTrack(true);
        MobclickAgent.setDebugMode(getConfig().isDebug());
        //微信
      /*  PlatformConfig.setWeixin(KeyConfig.WX_APP_KEY, KeyConfig.WX_APP_SECRET);

        //QQ
        PlatformConfig.setQQZone(KeyConfig.QQ_APP_ID, KeyConfig.QQ_APP_KEY);*/

        LogUtils.loge("MobclickAgent:" + TestDeviceUtil.getDeviceInfo(getContext()));
    }

    public static void initLoadingView(Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.layout_loan_loading, null);
        ViewUtil.setLoadingView(context, view);
    }

    public static void loadingDefault(Activity activity) {
        ViewUtil.setLoadingView(activity, null);
        ViewUtil.showLoading(activity, "");
    }

    public static void loadingContent(Activity activity, String content) {
        ViewUtil.setLoadingView(activity, null);
        ViewUtil.showLoading(activity, content);
    }

    public static void hideLoading() {
        ViewUtil.hideLoading();
    }


    public static String getAPPName() {
        return getContext().getResources().getString(R.string.app_name);
    }

    /*******
     * 将事件交给事件派发controller处理
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(BaseEvent event) {
        event.setApplicationContext(getContext());
        EventController.getInstance().handleMessage(event);
    }


    //保存一些常用的配置
    private static ConfigUtil configUtil = null;

    public static ConfigUtil getConfig() {
        if (configUtil == null) {
            configUtil = new ConfigUtil();
        }
        return configUtil;
    }

    public static void toLogin(Context context) {
        String uName = SpUtil.getString(Constant.CACHE_TAG_USERNAME);
        if (!TextUtils.isEmpty(uName) && StringUtil.isMobileNO(uName)) {
            Intent intent = new Intent(context, LoginActivity.class);
            intent.putExtra("tag", StringUtil.changeMobile(uName));
            intent.putExtra("phone", uName);
            context.startActivity(intent);
        } else {
            Intent intent = new Intent(context, RegisterPhoneActivity.class);
            context.startActivity(intent);
        }
        return;
    }

    public static Context getContext() {
        return mApp.getApplicationContext();
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public int dip2px(float dpValue) {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 获取进程号对应的进程名
     * @param pid
     *         进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }
}
